﻿using System;
using System.Collections.Generic;
using System.Linq;
using BLToolkit.Data.Linq;
using Calendar.Logic.ObjectModel;

namespace Calendar.Logic.ObjectManager
{
    public class EmailManager : BaseManager<EmailManager, Email>
    {
        public Email SelectNext()
        {
            return Table.Where(e => !e.Sent).FirstOrDefault();
        }

        public Email CreateInstance(string template, string to, Dictionary<string, string> parameters,List<int> attachs)
        {
            var email = CreateInstance();
            email.Template = template;
            email.To = to;
            email.DateIn = DateTime.Now;
            var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            email.Params = jss.Serialize(parameters);
            email.Attach = attachs != null ? jss.Serialize(attachs) : "";
            return email;
        }

        public int Create(string tmplate, string to, Dictionary<string, string> parameters, List<int> attachs)
        {
            var email = CreateInstance(tmplate, to, parameters, attachs);
            return Insert(email);
        }

        public void CreateBatch(string template, Dictionary<string, string> parameters, List<string> toList, List<int> attachs)
        {
            var emails = toList.Select(to => CreateInstance(template, to, parameters, attachs)).ToList();
            InsertBatch(emails);
        }


        public int Sent(int id)
        {
            return Table.Select(id).Set(e => e.Sent, true).Set(e => e.DateSend, DateTime.Now).Update();
        }

        public List<Email> SelectNotSent()
        {
            return Table.Where(e => e.Sent == false).OrderByDescending(e=>e.ID).ToList();
        }
    }
}
